package com.txby.pf.modules.job.utils;

import com.txby.pf.common.utils.SpringContextUtils;
import com.txby.pf.common.exception.RRException;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

/**
 * 执行定时任务
 */
public class RemidRunnable implements Runnable {
	private Object target;
	private Method method;
	private String params;
	private Long jobId;
	
	public RemidRunnable(String beanName, String methodName, String params,Long jobId) throws NoSuchMethodException, SecurityException {
		this.target = SpringContextUtils.getBean(beanName);
		this.params = params;
		this.jobId=jobId;
		
		if(StringUtils.isNotBlank(params)){
			this.method = target.getClass().getDeclaredMethod(methodName, String.class,Long.class);
		}else{
			this.method = target.getClass().getDeclaredMethod(methodName,String.class,Long.class);
		}
	}

	@Override
	public void run() {
		try {
			ReflectionUtils.makeAccessible(method);
			if(StringUtils.isNotBlank(params)){
				method.invoke(target, params,jobId);
			}else {
				if(!StringUtils.isNotBlank(params)){
					method.invoke(target, "",jobId);
				}else{
					method.invoke(target);
				}
			}
		}catch (Exception e) {
			throw new RRException("执行定时任务失败", e);
		}
	}

}
